package cn.objectspace.filessh.controller;

import cn.objectspace.filessh.pojo.SSHConnectUser;
import cn.objectspace.filessh.service.FileSshService;
import cn.objectspace.util.OperateString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ssh")
@CrossOrigin("*")
public class SshController {

    private FileSshService fileSshService;

    private SSHConnectUser sCU = new SSHConnectUser("123.249.80.146", 22, "root", "ZHL0521zhl..");

    @Autowired
    public SshController(FileSshService fileSshService) {
        this.fileSshService = fileSshService;
    }

    @PostMapping("/execute")
    @ResponseBody
    public String executeSshCommand(@RequestParam("command") String command) {
        if (OperateString.isEditCommand(command)) {
            return "请在网页终端编辑文件";
        } else {
            try {
                // 连接到SSH服务器
                fileSshService.connect(sCU.getHost(), sCU.getPort(), sCU.getUsername(), sCU.getPassword());

                // 执行SSH命令
                String commandOutput = fileSshService.executeCommand(command);

                // 断开SSH连接
                fileSshService.disconnect();

                return commandOutput;
            } catch (Exception e) {
                e.printStackTrace();
                return "SSH command execution failed.";
            }
        }

    }

    @PostMapping("/upload")
    @ResponseBody
    public String uploadAndSendFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("remotePath") String remotePath
    ) {
        try {
            // 连接到SSH服务器
            fileSshService.connect(sCU.getHost(), sCU.getPort(), sCU.getUsername(), sCU.getPassword());
            // 将上传的文件传输到远程服务器
            fileSshService.uploadFile(file, remotePath);
            // 断开SSH连接
            fileSshService.disconnect();
            return "操作成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "SSH file upload and command execution failed.";
        }
    }

    @PostMapping("/download")
    public void downloadFile(@RequestParam("filePath") String path, HttpServletResponse response) {
        try {
            // 连接到SSH服务器
            fileSshService.connect(sCU.getHost(), sCU.getPort(), sCU.getUsername(), sCU.getPassword());

            // 获取文件内容
            InputStream fileInputStream = fileSshService.downloadFile(path);

            // 设置响应头
            response.setHeader("Content-Disposition", "attachment; filename=\"" + path + "\"");
            response.setContentType("application/octet-stream");

            // 将文件内容写入响应
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流和断开SSH连接
            outputStream.close();
            fileInputStream.close();
            fileSshService.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            // 处理错误
        }
    }

    @PostMapping("/fileOperate")
    @ResponseBody
    public String fileOperate(@RequestParam("type") String type,
                              @RequestParam("operate") String operate,
                              @RequestParam("filePath") String filePath){
        String result="success";
        try {
            // 连接到SSH服务器
            fileSshService.connect(sCU.getHost(), sCU.getPort(), sCU.getUsername(), sCU.getPassword());
            if (type.equals("file")) {
                switch (operate) {
                    case "deleteFile":
                         fileSshService.executeCommand("rm -f "+filePath);
                        break;
                    case "newFile":
                         fileSshService.executeCommand("touch "+filePath);
                        break;
                    default:
                        result="文件路径错误或文件名错误!";
                }
            } else if (type.equals("document")) {
                switch (operate) {
                    case "deleteFolder":
                        fileSshService.executeCommand("rm -rf "+filePath);
                        break;
                    case "newFolder":
                        fileSshService.executeCommand("mkdir -p "+filePath);
                        break;
                    default:
                        result="文件路径错误或文件名错误!";
                }
            } else {
                result="操作错误!";
            }
            // 断开SSH连接
            fileSshService.disconnect();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "SSH command execution failed.";
        }
    }
    @PostMapping("/fileDirectory")
    @ResponseBody
    public String getCurrentFileDirectory(@RequestParam("path") String path){
        try {
            // 连接到SSH服务器
            fileSshService.connect(sCU.getHost(), sCU.getPort(), sCU.getUsername(), sCU.getPassword());

            List<Map<String, String>> maps = fileSshService.listFiles(path);

            // 断开SSH连接
            fileSshService.disconnect();
            return maps.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "SSH command execution failed.";
        }
    }
    @PostMapping("/searchFileAndFolder")
    @ResponseBody
    public String searchFileAndFolder(@RequestParam("directory") String directory,@RequestParam("searchContent") String searchContent,@RequestParam("isIncludeSubdirectory") Boolean isIncludeSubdirectory){
        try {
            // 连接到SSH服务器
            fileSshService.connect(sCU.getHost(), sCU.getPort(), sCU.getUsername(), sCU.getPassword());

            List<Map<String, String>> s = fileSshService.searchFilesInDirectoryAndSubdirectories(directory, searchContent,isIncludeSubdirectory);

            // 断开SSH连接
            fileSshService.disconnect();
            return s.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "SSH command execution failed.";
        }
    }

}
